using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using XFABManager;

namespace XFGameFramework.TweenSystem
{

    /// <summary>
    /// 动画序列
    /// </summary>
    public class TweenerSequence : CustomAsyncOperation<TweenerSequence>
    {

        #region 静态方法

        private static List<TweenerSequence> sequences = new List<TweenerSequence>();

        //[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
        //private static void InitTweener()
        //{
        //    sequences.Clear();
        //}

        static TweenerSequence() 
        {
            UpdateManager.AddUpdateEvent(SequenceUpdate);
        }


        private static void SequenceUpdate()
        {
            for (int i = 0; i < sequences.Count; i++)
            { 
                sequences[i].Update();
            }

            for (int i = sequences.Count - 1; i>= 0; i--)
            {
                if (sequences[i].isCompleted) 
                {
                    sequences.RemoveAt(i);
                }
            }
        }

        private static void Add(TweenerSequence sequence)
        { 
            sequences.Add(sequence);
        }

        private static void Remove(TweenerSequence sequence)
        {
            sequences.Remove(sequence);
        }
         
        #endregion



        #region 字段

        //private List<Tweener> tweeners = new List<Tweener>();

        private List<IList<Tweener>> tweeners = new List<IList<Tweener>>();

        private int index;

        [Tooltip("循环模式")]
        private LoopMode loopMode = LoopMode.Once;

        [Tooltip("循环次数(<=0表示一直循环!)")]
        private int loopCount = -1;
         
        private bool pingpong = false; // false 表示乒乓的开始 到 结尾 ，true 表示 结尾到开始


        private bool pause;

        private int currentLoopCount;

        #endregion


        #region 属性
         
        /// <summary>
        /// 循环模式
        /// </summary>
        public LoopMode LoopMode
        {
            get { 
                return loopMode;
            }
            set { 
                loopMode = value;
            }
        } 

        /// <summary>
        /// 循环次数( <=0 表示一直循环)
        /// </summary>
        public int LoopCount 
        {
            get { 
                
                return loopCount;
            }
            set { 
                loopCount = value;
            }
        }


#pragma warning disable IDE1006  
        public bool isPause 
        {
            get { 
                return pause;
            }
        
        }

        public bool isRunning { get; private set; } = false;

#pragma warning restore IDE1006


        public List<IList<Tweener>> Tweeners => tweeners;

        #endregion


        #region 事件

        public Action<TweenerSequence> onKill;

        #endregion

        #region 方法


        public void Append(Tweener tweener)
        {
            tweener.Pause(true);

            tweeners.Add(new Tweener[] { tweener });
        }

        public void Append(IList<Tweener> tweeners) 
        {
            foreach (var item in tweeners)
            {
                item.Pause(true);
            }

            this.tweeners.Add(tweeners);
        }

        /// <summary>
        /// 延迟
        /// </summary>
        /// <param name="interval"></param>
        public void AppendInterval(float interval) 
        {
            if (interval <= 0) return;

            Tweener tweener = new Tweener();
            tweener.LoopMode = LoopMode.Once;
            tweener.Duration = interval;
            tweener.Play();
            Append(tweener);
        }

        internal void Update() 
        {
            if (isCompleted) return;

            // 如果超出范围 把它设置为默认值
            if (index < 0 || index >= tweeners.Count)
                index = 0;


            for (int i = 0; i < tweeners.Count; i++) 
            {
                foreach (var item in tweeners[i])
                {
                    item.Pause(pause ? true : i != index); // 除了当前正在播放的动画，其他的动画全部暂停 
                     
                    if (item.LoopMode != LoopMode.Once && item.LoopCount <= 0)
                        item.LoopCount = 1; // 队列中的动画不能一直循环，所以这里设置成了1   
                }  
            }
             


            // 判断当前的动画有没有完成，如果完成了 播放下一个  

            if (IsDone(tweeners[index]))
            {
                switch (LoopMode)
                {
                    case LoopMode.Once:

                        if (index >= tweeners.Count - 1) 
                        {
                            Completed(); // 动画结束
                        }
                        index++;
                        break;
                    case LoopMode.Loop:
                        
                        if (index >= tweeners.Count - 1 && LoopCount > 0)
                        {
                            currentLoopCount++;

                            if(currentLoopCount >= LoopCount)
                                Completed();
                        }

                        index++;
                        break;
                    case LoopMode.Pingpong:
                        if (!pingpong)
                        {
                            if (index >= tweeners.Count - 1) 
                            {  
                                pingpong = !pingpong; // 说明是最后一个 ，反向 
                                index = tweeners.Count - 1;
                            }
                            else 
                                index++;
                        }
                        else
                        { 
                            if (index <= 0)
                            {
                                pingpong = !pingpong;

                                if (LoopCount > 0)
                                {
                                    currentLoopCount++;

                                    if (currentLoopCount >= LoopCount)
                                        Completed();
                                }
                            }
                            else 
                            {
                                index--;
                            }
                        }
                        break; 
                }


                if (index < 0 || index >= tweeners.Count)
                    index = 0;

                // 序列没执行完成的时候 当前动画不在运行中 启动一下动画
                if (!isCompleted && !IsRunning(tweeners[index]))  
                { 
                    foreach (var item in tweeners[index])
                    {
                        item.Play(); // 如果当前这个动画已经完成了 重新启动一下
                    }
                }
            }


        }


        private bool IsDone(IList<Tweener> tweeners) 
        {
            foreach (var item in tweeners)
            {
                if(!item.isDone)
                    return false;
            }

            return true;
        }


        private bool IsRunning(IList<Tweener> tweeners) 
        {
            foreach (var item in tweeners)
            {
                if (!item.isRuning)
                    return false;
            }
            return true;
        }

        public void Play()
        {
           
            if (tweeners == null || tweeners.Count == 0)
                return;

            if (isRunning) return;
             
            isRunning = true;

            index = 0;
            currentLoopCount = 0;

            isCompleted = false;


            // 把第一组动画启动

            if (tweeners.Count > 0) 
            {
                foreach (var item in tweeners[0])
                {
                    item.Play();
                }
            }

            Add(this);
        }

        /// <summary>
        /// 暂停
        /// </summary>
        /// <param name="pause">true:暂停 false:取消暂停</param>
        public void Pause(bool pause) 
        {
            this.pause = pause;
        }

        [Obsolete("已过时,请使用Kill方法代替!")]
        public void Stop() 
        {
            Kill();
        }

        public void Kill() 
        {
            if (!isRunning) return; // 只有在运行中才能够停止  
            KillWithoutNotify(); 
            // 触发事件
            onKill?.Invoke(this); 

        }

        private void KillWithoutNotify() 
        {
            if (!isRunning) return; // 只有在运行中才能够停止  
            CompletedWithoutNotify();
            Remove(this);

            // 中断所有动画
            foreach (var item in tweeners)
            {
                if (item == null) continue;

                foreach (var t in item)
                {
                    if(t == null) continue;

                    t.Kill();
                }
            } 
        }


        public void Clear() 
        {
            KillWithoutNotify();
            tweeners.Clear();
        }

        protected override void OnCompleted()
        {
            base.OnCompleted(); 
            isRunning = false; 
        }

        #endregion

    }

}

